package com.example.chatplatform.ws;

import com.alibaba.fastjson.JSON;
import com.example.chatplatform.config.GetHttpSessionConfig;
import com.example.chatplatform.model.entity.WebMessage;
import com.example.chatplatform.service.WebsocketService;
import com.example.chatplatform.util.MessageUtils;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfig.class)
public class ChatEndpoint {

    private static WebsocketService websocketService;

    @Autowired
    public void setWebsocketService(WebsocketService service) {
        ChatEndpoint.websocketService = service;
    }

    private static final Map<Integer, Session> onlineUsers = new ConcurrentHashMap<>();


    private static final Map<Integer, Set<Session>> onlineGroupUsers = new ConcurrentHashMap<>();

    private HttpSession httpSession;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {

        //将session进行保存
        httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        Integer userId = (Integer) httpSession.getAttribute("userId");
        onlineUsers.put(userId, session);

        System.out.println("用户" + userId + "已登录");

        //添加群聊用户session
        List<Integer> groupList =  websocketService.GroupId(userId);
        for (Integer groupId : groupList) {
            onlineGroupUsers.computeIfAbsent(groupId, k -> new CopyOnWriteArraySet<>())
                    .add(session);
        }

    }

    @OnMessage
    public void onMessage(String message) {
        try {
            //将消息推送给指定用户
            WebMessage webMessage = JSON.parseObject(message, WebMessage.class);

            if (Objects.equals(webMessage.getType(), "crony")) {
                //获取消息接收方的session对象
                Session session1 = onlineUsers.get(webMessage.getToId());
                Integer userId = (Integer) httpSession.getAttribute("userId");
                Session session0 = onlineUsers.get(userId);

                String msg1 = MessageUtils.getMessage(1, webMessage.getType(), userId, webMessage.getMessage());
                String msg0 = MessageUtils.getMessage(0, webMessage.getType(), webMessage.getToId(), "已发送");

                websocketService.addCronyMessage(userId, webMessage.getToId(), webMessage.getMessage());
                if (session1 != null) {
                    session1.getAsyncRemote().sendText(msg1);
                }
                session0.getAsyncRemote().sendText(msg0);
            } else if (Objects.equals(webMessage.getType(), "group")) {

                Integer userId = (Integer) httpSession.getAttribute("userId");
                Session session = onlineUsers.get(userId);

                String msg1 = MessageUtils.getMessage(1, webMessage.getType(), webMessage.getToId(), webMessage.getMessage());
                String msg0 = MessageUtils.getMessage(0, webMessage.getType(), webMessage.getToId(), "已发送");

                websocketService.addGroupMessage(webMessage.getToId(), userId, webMessage.getMessage());

                // 群组消息广播方法
                Set<Session> groupMembers = onlineGroupUsers.get(webMessage.getToId());
                if (groupMembers != null) {
                    for (Session member : groupMembers) {
                        if (member.isOpen()) {
                            if (member != session) {
                                System.out.println(msg1);
                                //发送给成员
                                member.getAsyncRemote().sendText(msg1);
                            } else {
                                System.out.println(msg0);
                                //发送给自己
                                member.getAsyncRemote().sendText(msg0);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    @OnClose
    public void onClose(Session session) {
        Integer userId = (Integer) httpSession.getAttribute("userId");
        System.out.println("用户" + userId + "连接已关闭");
        onlineUsers.remove(userId);
        onlineGroupUsers.values().forEach(set -> set.remove(session));
    }

    //判断用户登录
    public boolean onlineUser(Integer userId) {
        return onlineUsers.containsKey(userId);
    }

}
